﻿using System;
using System.Collections.Generic;
using System.IO;
using SVNClean.Properties;

namespace SVNClean.Modules {
    public static class SvnDirectoryNames {

        /// <summary>
        /// Gets or sets the names.
        /// </summary>
        /// <value>The names.</value>
        public static NameCollection Names { get; set; }

        /// <summary>
        /// Gets the file names path.
        /// </summary>
        /// <value>The file names path.</value>
        private static string FileNamesPath {
            get { return Environment.CurrentDirectory + Resources.NameListPath; }
        }

        /// <summary>
        /// Saves the list.
        /// </summary>
        public static void SaveList() {
            if (File.Exists(FileNamesPath)) File.Delete(FileNamesPath);
            if (!Directory.Exists(Environment.CurrentDirectory + Resources.ConfigDirectory)) {
                Directory.CreateDirectory(Environment.CurrentDirectory + Resources.ConfigDirectory);
            }
            string xml = Names.Serialize();
            var sw = new StreamWriter(FileNamesPath);
            try {
                sw.Write(xml);
                sw.Flush();
            }
            finally { sw.Close(); }
        }

        /// <summary>
        /// Loads the list.
        /// </summary>
        public static void LoadList() {
            if (File.Exists(FileNamesPath)) {
                var sr = new StreamReader(FileNamesPath);
                try {
                    var xml = sr.ReadToEnd();
                    Names = (NameCollection)xml.Deserialize(typeof(NameCollection));
                }
                finally { sr.Close(); }
            }
            else {
                Names = new NameCollection { ".svn", "_svn" };
                SaveList();
            }
        }

        /// <summary>
        /// Determines whether [is SVN directory] [the specified path].
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>
        /// 	<c>true</c> if [is SVN directory] [the specified path]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsSvnDirectory(this string path) {
            List<string> dirs = new List<string>();
            dirs.AddRange(path.Split(new char[] { Convert.ToChar("\\") }));
            dirs.Reverse();
            if (dirs.Count > 0) {
                return Names.Contains(dirs[0]);
            }
            return false;
        }

    }
}
